<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button onclick="back()">后退</button>
  <button onclick="forward()">前进</button>
  <div style="margin-top: 10px;">
    <button onclick="push('/home')">去home页面</button>
    <button onclick="push('/classify')">去classify页面</button>
  </div>
  <div id="root"></div>
  <script type="text/javascript" src="https://cdn.bootcss.com/history/4.7.2/history.js"></script>
  <script type="text/javascript">

    // const history = History.createBrowserHistory()  //H5推出的history身上的API，低版本浏览器可能不支持
    const history = History.createHashHistory()  //hash值（锚点），兼容性好

    // 路由跳转
    const push = path => history.push(path)

    // 路由替换
    const replace = path => history.replace(path)

    // 路由回退
    const back = () => history.goBack()

    // 路由前进
    const forward = () => history.goForward()

    // 路由变化监听
    history.listen(location => {
      console.log('监听到路由栈变化', location);
      render(location.pathname)
    });

    const render = (function render(pathname) {
      const pages = {
        "/home": "<h1>这是home页面</h1>",
        "/classify": "<h1>这是classify页面</h1>"
      }
      const root = document.getElementById('root')
      root.innerHTML = pages[pathname]
      return render
    })(`/${location.hash.replace("#", "").replace("/", "") || 'home'}`)
  </script>
</body>

</html>